package xyz.longicorn.driver.dao;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import xyz.longicorn.driver.pojo.LoginUser;

import java.util.concurrent.TimeUnit;

@Component
public class LoginUserDao {
    private final String REDIS_PREFIX = "driver:user:token:";
    private final RedisTemplate redisTemplate;

    public LoginUserDao(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private String buildTokenKey(String token) {
        return REDIS_PREFIX + token;
    }

    public void refreshToken(String token) {
        refreshToken(token, 1800);
    }

    public void refreshToken(String token, long timeout) {
        redisTemplate.expire(buildTokenKey(token), timeout, TimeUnit.SECONDS);
    }

    public LoginUser save(LoginUser user) {
        return save(user, 1800);
    }

    public LoginUser save(LoginUser user, long timeout) {
        //更改在redis里面查看key编码问题
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        try {
            String userJson = (new ObjectMapper()).writeValueAsString(user);
            vo.set(buildTokenKey(user.getToken()), userJson, timeout, TimeUnit.SECONDS);//设置key并且设置有效时间
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return user;
    }

    public LoginUser get(String token) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        final Object o = vo.get(buildTokenKey(token));
        if (null != o) {
            try {
                return (new ObjectMapper()).readValue(o.toString(), LoginUser.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public boolean exists(String token) {
        return redisTemplate.hasKey(buildTokenKey(token));
    }

    void deleteByToken(String token) {
        redisTemplate.delete(buildTokenKey(token));
    }

    void delete(LoginUser user) {
        deleteByToken(user.getToken());
    }
}
